import axios from 'axios';
import type { AxiosInstance, AxiosResponse } from 'axios';

// 定义扩展的请求实例接口
interface ExtendedAxiosInstance extends AxiosInstance {
	exportFile(url: string, params: any): Promise<AxiosResponse<Blob>>;
}

/* 通用响应格式 */
interface ApiResponse<T = any> {
	code: number;
	data: T;
	message: string;
}

interface RequestOptions {
	baseURL: string; // 完整 http(s) 地址
	getToken?: () => string | null | Promise<string | null>;
	withCredentials?: boolean;
}

export function createRequest(opts: RequestOptions): ExtendedAxiosInstance {
	const ins = axios.create({
		baseURL: opts.baseURL,
		timeout: 10000,
		headers: { 'Content-Type': 'application/json' },
		withCredentials: opts.withCredentials ?? false // ← 传给 axios
	}) as ExtendedAxiosInstance;

	/* 请求拦截：挂 token */
	ins.interceptors.request.use(async (config) => {
		if (opts.getToken) {			
			// 浏览器 Cookie 模式不传 getToken 就不会进来
			const t = await opts.getToken();		
			if (t) config.headers.set('token', t);
		}
		return config;
	});

	/* 响应拦截：统一拆 data + 业务码 */
	ins.interceptors.response.use(
		(res: AxiosResponse<ApiResponse>) => {
			const body = res.data;
			/**************** 加body.code &&主要是为了当请求的data直接返回一个字符串，没有code的时候，不会报错，后续看是否需要修正 **************/
			if (body.code && body.code !== 200) return Promise.reject(body);
			return body.data ?? body;
		},
		(err) => {
			/* 网络 / 状态码 错误统一处理（保持你原来逻辑） */
			let msg = '网络连接错误';
			const status = err.response?.status;
			if (status === 401) {
				msg = '未授权，请重新登录';
				window.location.href = '/logout';
			} else if (status === 403) msg = '无权访问';
			else if (status === 404) msg = '请求地址错误';
			else if (status >= 500) msg = '服务器内部错误';
			console.error('[request]', msg, err);
			return Promise.reject(err);
		}
	);

	/* 扩展：文件导出 */
	ins.exportFile = (url: string, data: any) => ins.post(url, data, { responseType: 'blob' });

	return ins as any;
}
